package com.ica.android.ui.contact;

import java.util.Iterator;
import java.util.List;

import com.ica.R;
import com.ica.android.ui.contact.util.AndroidContact;
import com.ica.android.ui.contact.util.ContactConversor;
import com.ica.model.contact.Contact;
import com.ica.model.contact.ContactGroup;
import com.ica.model.facade.ContactFacadeMockImpl;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

/**
 * @author   Hector
 */
public class EditContactGroupActivity extends ContactGroupActivity {
	
	/**
	 * @uml.property  name="contactFacade"
	 * @uml.associationEnd  
	 */
	private final ContactFacadeMockImpl contactFacade = ContactFacadeMockImpl.getInstance();
	/**
	 * @uml.property  name="contactGroup"
	 * @uml.associationEnd  
	 */
	private ContactGroup contactGroup = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {	
        super.onCreate(savedInstanceState);
        init(R.layout.edit_contact_group);
        Bundle extras = getIntent().getExtras();
        long contactGroupId = (Long) extras.get("contactGroupId");
        contactGroup = contactFacade.getElement(contactGroupId);
        etName.setText(contactGroup.getName());
        
    }
	
	private AndroidContact getAndroidContactById(long id) {	
		for(AndroidContact contact : contacts) {
			if (contact.getId()==id) return contact;
		}
		return null;
	}
	
	@Override
	protected Runnable getAfterFillList() {
		return new Runnable() {		
			public void run() {		
				if(contacts != null && contacts.size() > 0) {
					Iterator<Contact> currentContacts = contactGroup.getContacts();
					while (currentContacts.hasNext()) {
						Contact current = currentContacts.next();
						AndroidContact inList = getAndroidContactById(current.getId());
						if (inList != null) {
							inList.setChecked(true);
						}
					}
		            adapter.notifyDataSetChanged();
		        }
		        progressDialog.dismiss();		
			}
		};
	}

	@Override
	protected OnClickListener onClickSave() {	
		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {
				if (etName.getText().toString().equals(""))
					Toast.makeText(EditContactGroupActivity.this, "The Contacts Group's name is required", Toast.LENGTH_SHORT).show();
				else {
					contactGroup.setName(etName.getText().toString());
					List<Contact> selectedContacts = ContactConversor.toContact(getSelectedContacts());
					contactGroup.replaceContacts(selectedContacts);
					contactFacade.replaceElement(contactGroup.getId(), contactGroup);
					setResult(RESULT_OK,null);
					finish();	
				}
			}
		};
		return listener;
	}
}
